package com.zyl.Ecs.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;

import java.time.LocalDateTime;

/**
 * @version v1.0
 * @ProjectName: Ecs
 * @Package: com.zyl.Ecs.common.handler
 * @ClassName: a
 * @Description
 *      MyBatisPlus自定义字段拦截器
 *      为实体类中部分字段自动填充/更新值。
 * @Author 翟玉龙
 * @Date 2024/12/6-14:07
 */
@PropertySource("classpath:application-common.yml")
public class MyBatisPlusFillingHandler implements MetaObjectHandler {

    /**
     * 以下属性均从配置文件中读取数值
     */
    @Value("${mybatis-plus.global-config.db-config.logic-delete-field}")
    private String logicDeleteField;
    @Value("${mybatis-plus.global-config.db-config.logic-not-delete-value}")
    private Integer logicNotDeleteValue;
    @Value("${zyl.config.entity.create-time-field}")
    private String createTimeField;
    @Value("${zyl.config.entity.update-time-field}")
    private String updateTimeField;

    /**
     * 新增数据时的填充操作
     *
     * @param metaObject 填充对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        /* 新增时处理，默认设置为0（未删除） */
        strictInsertFill(metaObject, logicDeleteField, Integer.class, logicNotDeleteValue);

        /* 新增数据时自动填充createTime和updateTime字段为当前时间 */
        strictInsertFill(metaObject, createTimeField, LocalDateTime.class, LocalDateTime.now());
        strictInsertFill(metaObject, updateTimeField, LocalDateTime.class, LocalDateTime.now());
    }

    /**
     * 修改数据时的填充操作
     *
     * @param metaObject 填充对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        /* 修改数据时自动修改modifyTime字段为当前时间 */
        strictInsertFill(metaObject, updateTimeField, LocalDateTime.class, LocalDateTime.now());
    }
}